package org.example.controller;

import jakarta.annotation.Resource;
import org.example.entity.Cart;
import org.example.entity.CommonResult;
import org.example.service.CartService;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RefreshScope
public class CartController {
    @Resource
    private CartService cartService;

    @PostMapping("/CartController/addCart")
    public CommonResult<Cart> addCart(
            @RequestParam("uid") String uid,
            @RequestParam("bid") String bid,
            @RequestParam("fid") Integer fid
    ) {
        //注意这里 uid、bid、fid肯定是需要本身存在在数据库中的，而不能是凭空的。
        // 但是在这里的前端界面上，到了这一步，获取到的这些id肯定都是存在的。
        //我觉得最稳妥的话，就是调用其他微服务的 查找
        Cart cart = cartService.addCart(uid,bid,fid);
        if(cart != null){
            return new CommonResult<>(200, "创建购物车成功", cart);
        }else{
            return new CommonResult<>(404, "创建购物车失败", null);
        }
    }

    //  CartController/updateCart
    @GetMapping("/CartController/updateQuantity/{uid}/{bid}/{fid}/{q}")
    public CommonResult<Cart> updateQuantity(@PathVariable("uid") String uid,
                               @PathVariable("fid") Integer fid,
                               @PathVariable("bid") Integer bid,
                               @PathVariable("q") Integer q) {
        Cart cart = cartService.updateQuantityByBidAndUidAndFid(uid, fid, bid, q);
        if(cart != null){
            return new CommonResult<>(200, "修改购物车数量成功", cart);
        }else{
            return new CommonResult<>(404, "购物车不存在，无法修改", null);
        }

    }
//
    @PostMapping("/CartController/findAllByUidOrByUidAndBid") //CartController/listCart
    public CommonResult<List> findAllByUidOrByUidAndBid(@RequestParam("uid") String uid,
                                                @RequestParam(value ="bid" ,required = false) String bid) {
        //这里的get方法,如果使用@RequestParam这个注解, 就一定需要去apifox的body传参(form形式),且是原始网址.  可选参数都按照这个套路来写
        List<Cart> carts = cartService.findAllByUidOrByUidAndBid(uid, bid);
        if(carts != null){
            return new CommonResult<>(200, "查找购物车成功", carts);
        }else{
            return new CommonResult<>(404, "无法查找相应购物车", null);
        }
    }
    @PostMapping("/CartController/removeCart")
    public CommonResult<Integer> deleteByUidAndBidAndFidOrByUidAndBid(@RequestParam("uid") String uid,
                                                     @RequestParam("bid") String bid,
                                                     @RequestParam(value ="fid" ,required = false) Integer fid){
        cartService.deleteByUidAndBidAndFidOrByUidAndBid(uid, bid, fid);
        return new CommonResult<>(200, "删除成功", null);
    }
}